package com.example.mediamoudle.scrollview

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.android.baselibrary.base.BaseActivity
import com.android.baselibrary.utils.dp2px
import com.android.baselibrary.utils.getDurationString
import com.example.mediamoudle.R
import com.example.mediamoudle.crop.RecyclerDivider
import com.example.mediamoudle.crop.ThumbAdapter
import com.example.mediamoudle.crop.VideoCropActivity
import com.example.mediamoudle.crop.VideoInfo
import com.example.mediamoudle.databinding.ActivityVideoScrollBinding
import com.example.mediamoudle.router.MediaRouterPath
import com.example.mediamoudle.utlis.MediaUtils

/**
 * 本地视频
 */
@Route(path = MediaRouterPath.MEDIA_SCROLLVIEW)
class ScrollVideoActivity :BaseActivity<ActivityVideoScrollBinding>(),View.OnClickListener{
    companion object{
        const val VIDEO_URL = "/storage/emulated/0/DCIM/Camera/20221115_134123.mp4"
    }
    override fun getLayoutId(): Int {
      return R.layout.activity_video_scroll
    }
    /** 缩略图*/
    private var thumnlist = ArrayList<VideoInfo>()
    /**缩略图adapter*/
    private var mAdapter: ThumbAdapter? = null
    private var duration:Long = 0L;
    private var mThumbHeight = 50
    private var lastDistance = 0
    override fun initView() {
        mThumbHeight = dp2px(this,mThumbHeight);
        duration =  MediaUtils.getVideoDuration(this, VIDEO_URL);
        mBinding.tvEndDuration.text = getDurationString(duration)
        mBinding.progressBar.max = (duration/1000).toInt()
        playVideo(VIDEO_URL)

    }
    private fun playVideo(stringExtra: String) {
        if (TextUtils.isEmpty(stringExtra)) {
            Toast.makeText(this, "文本路径错误", Toast.LENGTH_SHORT).show()
        } else {
            mBinding.imagePlayControl.isSelected = false
            mBinding.imagePlay.visibility =  View.GONE
            mBinding.videoPreview.seekTo(0)
            mBinding.videoPreview.setVideoPath(stringExtra)
            mBinding.videoPreview.setOnPreparedListener { mp ->
                mBinding.imagePlay.visibility = View.VISIBLE
                Log.i(VideoCropActivity.TAG, "playVideo: time ->${mBinding.videoPreview.duration}")
            }
            mBinding.videoPreview.setOnCompletionListener {
                mBinding.imagePlayControl.isSelected = true
                mBinding.imagePlay.visibility = View.VISIBLE
            }

        }
        // 通过视频获取缩略图
        thumnlist.clear()
        thumnlist.add(VideoInfo(0))
        getGetFrameAtTime(0)
    }
    private fun getGetFrameAtTime(time: Long) {

        if (time >= duration/1000) {
            // 如果超过了就返回，不要截取了
            initPic()
            return
        }
        val nextTime = time + 1
        var targetFrame = time.toLong() * 1000000
        if (targetFrame > 0) {
            targetFrame += 1000000
        }
        if (targetFrame<=duration*1000000){
            thumnlist.add(VideoInfo(targetFrame, VideoCropActivity.VIDEO_URL,1))
            getGetFrameAtTime(nextTime)
        }
    }
    private fun initPic(){
        mBinding.mRecyclerView.visibility = View.VISIBLE
        mAdapter = ThumbAdapter()
        // 添加时间轴
        mBinding.mRecyclerView.addItemDecoration(RecyclerDivider(com.android.baselibrary.R.color.color_808080))
        thumnlist.add(VideoInfo(0))
        mAdapter?.updateList(thumnlist as List<VideoInfo>)
        val layoutManagers =  LinearLayoutManager(this@ScrollVideoActivity, LinearLayoutManager.HORIZONTAL, false)

        mBinding.mRecyclerView.apply {
            layoutManager = layoutManagers

            adapter = mAdapter
            isNestedScrollingEnabled = false

        }
        mBinding.mRecyclerView.setHasFixedSize(true)


    }

    override fun onClick(v: View?) {
        when(v?.id){
            /**点击播放**/
            R.id.image_play ->{
                mBinding.imagePlay.visibility = View.GONE
                mBinding.videoPreview.start()
                mBinding.imagePlayControl.isSelected = false
                startHandler()
                //videoBottomDialog?.show()
            }
            /**暂停and播放按钮**/
            R.id.image_play_control ->{
                mBinding.imagePlayControl.isSelected = mBinding.videoPreview.isPlaying
                mBinding.imagePlay.visibility = if (mBinding.videoPreview.isPlaying) View.VISIBLE else View.GONE
                if (mBinding.videoPreview.isPlaying){
                    mBinding.videoPreview.pause()
                }else{
                    mBinding.videoPreview.start()
                    startHandler()
                }
            }
        }
    }

    override fun initListener() {
        mBinding.imagePlay.setOnClickListener(this)
        mBinding.imagePlayControl.setOnClickListener(this)
        mBinding.videoPreview.setOnClickListener {
            if (mBinding.videoPreview.isPlaying){
                mBinding.imagePlay.visibility = View.VISIBLE
                mBinding.videoPreview.pause()
                mBinding.imagePlayControl.isSelected = true
            }
        }
        mBinding.scrollView.setScrollChange { left, top, oldLeft, oldTop ->
            Log.i("TAGScrollview", "initListener: left:$left,top:$top,oldLeft:$oldLeft,oldTop:$oldTop")
            lastDistance = left;
        }


    }
    /**
     * * @Description 发送消息更新进度条
     * @Author yf
     * @Date 2022/11/15 13:50
     */
    private fun startHandler(){
        if (mBinding.videoPreview.isPlaying){
            handler.sendEmptyMessageDelayed(VideoCropActivity.MESSAGE,50)
        }

    }
    /**
     * * @Description 更新进度条
     * @Author yf
     * @Date 2022/11/15 13:50
     */
    private val handler: Handler = @SuppressLint("HandlerLeak")
    object : Handler(){
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                VideoCropActivity.MESSAGE ->{
                    val current =  mBinding.videoPreview.currentPosition
                    //   Log.i("TAGas", "initPic1: ${px2dp(this@VideoCropActivity,(mBinding.mRecyclerView.layoutManager as LinearLayoutManager).getChildAt(0)?.measuredWidth!!)}")

                    mBinding.tvBeginDuration.text = getDurationString((current).toLong())
                    mBinding.progressBar.secondaryProgress = (current/1000)
                    mBinding.progressBar.progress =  (current/1000)
                    // move(current)
                    freshUI()
                    startHandler()
                }
            }
        }
    }
    private fun freshUI() {
        window.decorView.post {
            if (!mBinding.imagePlayControl.isSelected){
                val currentPosition = mBinding.videoPreview.currentPosition
                Log.i("TAGas", "currentPosition:$currentPosition")
                val correctScrollX: Int = (mThumbHeight / 1000f * currentPosition).toInt()
                Log.i("TAGas", "smoothScrollBy:${correctScrollX-lastDistance}")

                mBinding.scrollView.smoothScrollBy(correctScrollX-lastDistance,0);
            }
        }
    }
}